<?php
/**
 * @author: zhouzhongyuan <435690026@qq.com>
 */


namespace webservice\controllers;


use ReflectionClass;
use webservice\helpers\WebService;
use Yii;
use yii\filters\ContentNegotiator;
use yii\web\Controller;
use yii\web\Response;

class WebServiceController extends Controller
{
    public function init()
    {
        parent::init();

    }

    /**
     * @var string|array the configuration for creating the serializer that formats the response data.
     */
    public $serializer = 'webservice\helpers\Serializer';

    public $enableCsrfValidation = false;
    /**
     * @var null|\webservice\helpers\WebService
     */
    protected $soap = null;

    public function behaviors()
    {
        return [
            'contentNegotiator' => [
                'class' => ContentNegotiator::className(),
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                    'application/xml' => Response::FORMAT_XML,
                ],
            ],
        ];
    }

    public function afterAction($action, $result)
    {
        $result = parent::afterAction($action, $result);
        $result = $this->serializeData($result);

        $class = new ReflectionClass($result);//建立 Person这个类的反射类
        $instance = $class->newInstanceArgs();


        if (WebService::isSoap()) {
            $this->soap->handle($instance);
        } else {
            $ec = $class->getmethod('get');  //获取Person 类中的getName方法
            $ec->invoke($instance);       //执行getName 方法
            return $result;
        }

    }


    public function beforeAction($action)
    {
        $result = parent::beforeAction($action);
        if (WebService::isSoap()) {
            $this->soap = new WebService();
        }
        return $result;
    }

    protected function verbs()
    {
        return [];
    }


    protected function serializeData($data)
    {
        return Yii::createObject($this->serializer)->serialize($data);
    }
}